package com.wantup.springboot.boot.contorller;

import com.wantup.springboot.boot.beans.TxPerson;
import com.wantup.springboot.boot.service.TxPersonService;
import com.wantup.springboot.boot.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2018/11/12 15:51
 */
@Controller
public class PersonController {

    @Autowired
    private TxPersonService txPersonService;

    /**
     * 获取用户全部数据
     *
     * @param model
     * @return
     */
    @GetMapping("main")
    public String index(Model model) {
        List<TxPerson> allEmp = this.txPersonService.getAllEmp();

        model.addAttribute("pList", allEmp);

        return "main";
    }


    /**
     * 根据 id  获取一个 用户的信息
     *
     * @param pid
     * @param model
     * @return
     */
    @GetMapping("getPerson")
    public String getPerson(int pid, Model model) {
        String trans = "";
        try {
            TxPerson txPerson = this.txPersonService.getTxPersonById(pid);
            model.addAttribute("p", txPerson);
            trans = "update";
        } catch (Exception e) {
            e.printStackTrace();
            trans = "error";
        }

        return trans;
    }

    /**
     * @param txPerson
     * @return
     */
    @PostMapping("update")
    public String updateTxPerson(TxPerson txPerson) {
        String trans = "";
        try {
            System.out.println("前台的参数 ：" + txPerson);
            this.txPersonService.updateTxPerson(txPerson);

            trans = "redirect:index";
        } catch (Exception e) {
            e.printStackTrace();
            trans = "error";
        }


        return trans;
    }



    @PostMapping("save")
    public String save(TxPerson txPerson) throws Exception {
        this.txPersonService.addTxPerson(txPerson);
        return "redirect:main";
    }


    @GetMapping("delete")
    public String delete(int pid){
        try {
            this.txPersonService.deleteTxPerson(pid);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "redirect:main";
    }


}
